<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script src="static/jquery.min.js"></script>
    <!-- <script src="static/jq_IE8/jquery-1.4.2/jquery.min.js"></script> -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js"></script>
    <script src="static/codehandle.js"></script>
    <title>输液机器人测试平台</title>

    <style>
        .container {
            display: flex;
            height: 100vh;
        }

        .func_container {
            flex: 6;
            display: flex;
            flex-direction: row;
            flex-wrap: wrap;
            overflow: auto;
            /* justify-content: space-around; */
        }

        .item_container {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;          
            padding: 60px;
            margin: 10px 10px;
            width: 300px;
            height: 320px;
            text-align: center;
            border-radius: 5px;
            border: 1px solid gray;
        }

        .messge_container {
            flex: 4;
            max-width: 30%;
            display: flex;
            flex-direction: column;
            flex-wrap: wrap;
            height: 100vh;
            background-color: whitesmoke;
            border: 1px solid gray;
            border-radius: 5px;
            padding: 10px;
        }

        .message_item {
            width: 100%;
            word-wrap: break-word;
            overflow-wrap: break-word;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.4);
        }

        /* 模态框内容样式 */
        .modal-content {
            width: 60%;
            background-color: #fefefe;
            margin: 10% auto;
            padding: 20px;
            border: 1px solid #888;
        }

        /* 关闭按钮样式 */
        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }

        .close:hover,
        .close:focus {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }
    </style>

    <script type="text/javascript" language="javascript">

        String.prototype.startWith = function (str) {
            var reg = new RegExp("^" + str);
            return reg.test(this);
        }

        window.onload = function () {
            loadInfusionInfo();
        }

        function uint8ArrayToString(uint8Array) {
            let str = '';
            for (let i = 0; i < uint8Array.length; i++) {
                str += String.fromCharCode(uint8Array[i]);
            }
            return str;
        }

        // 加密函数
        function encryptData(data, key) {
            const sKey = CryptoJS.enc.Utf8.parse(key);
            const sValue  = CryptoJS.enc.Utf8.parse(data);
            const encrypted = CryptoJS.AES.encrypt(sValue, sKey, {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7});
            return encrypted.toString();
        }

        // 解密函数
        function decryptData(encryptedData, key) {
            const sKey = CryptoJS.enc.Utf8.parse(key);
            const decrypt = CryptoJS.AES.decrypt(encryptedData, sKey, {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7});
            const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
            return decryptedStr.toString();
        }
        
        
        function loadInfusionBottles() {
            //console.log("开始加载输液信息");

            const timestamp = Date.now();
            //console.log(timestamp); // 输出例如：1611815042339

            var key = "l8hI1TJfjxiUWSPs"
            var encodeData = encryptData("" + timestamp, key);
           // console.log("Encrypted data base64: " + encodeData)

            // 解密测试
            //const decryptedData = decryptData(encodeData, key);
            //console.log('Decrypted data:', decryptedData);

            // 请求体内容
            var body = { "robotCode": "ROBOT_9020ab3797670000000038FFD20530574D3123602043" };

            $.ajax({
                type: "GET",
                //dataType: "json",               
                timeout: 30000,
                headers: {                    
                    "keyId": "2+DmyLnYl2WypAfMghaS8w==",
                    "timeMillis": encodeData,
		    'Content-Type': 'application/json'
                },
                url: 'http://120.79.181.201/server/infusion/robot/getInfoByRobotCode?robotCode=ROBOT_9020ab3797670000000038FFD20530574D3123602043',
                //data: body,
                success: function (result) {
                    console.log("收到服务器响应:")
                    console.dir(result)
                    //var bottleInfos = result.data.bottleInfos // 获取输液瓶信息
                    updateUi(result)                 
                },
                error: function (result) {
                    console.log("收到错误消息:")
                    console.log(result)
                }
            });
        }

        function loadInfusionInfo() {
            this.loadInfusionBottles()
            setInterval(this.loadInfusionBottles, 3000)
        }

        function updateUi(result) {
            var listDiv = document.getElementById("list")
                while (listDiv.firstChild) {
                  listDiv.removeChild(listDiv.firstChild); // 循环删除该 div 的第一个子节点，直到没有子节点为止
                }
                
            var robotStatus = result.data.robotStatus
            if (robotStatus == 0) {
              alert("输液机器人发生报警，请及时处理")
            }
            
            var bottleInfos = result.data.bottleInfos
            for (let i = 0; i < bottleInfos.length; i++) {
                var infusionBottle = bottleInfos[i]
                //console.log(infusionBottle)
                var remainTime = infusionBottle.remainTime
                
                var child = document.createElement('div');
                child.className = "item_container"

                var bottleIndexView = document.createElement("h2")
                bottleIndexView.textContent = "瓶号: " + "第" + infusionBottle.bottleNumber + "瓶"

                var drugNameView = document.createElement("h3")
                drugNameView.textContent = "名称： " + infusionBottle.drugName

                var drugCapacityView = document.createElement("h3")
                drugCapacityView.textContent = "容量: " + infusionBottle.capacity + "ml"

                var remainCapacityView = document.createElement("h3")
                if (infusionBottle.remainCapacity != null) {
                  remainCapacityView.textContent = "剩余容量: " + infusionBottle.remainCapacity + "ml"
                }
                
                if (remainTime != null) {
                  var remainTimeView = document.createElement("h3")                 
                  var duration = ""
                  var hour = Math.floor(remainTime / 3600)
                  if (hour < 10) {
                    duration += "0" + hour 
                  } else {
                    duration += hour
                  }
                  duration += ":"
                  
                  var minute = Math.floor((remainTime % 3600) / 60)
                  if (minute < 10) {
                    duration += "0" + minute
                  } else {
                    duration += minute
                  }
                  duration += ":"
                  
                  var seconds = Math.floor(remainTime % 60)
                  if (seconds < 10) {
                    duration += "0" + seconds
                  } else {
                    duration += seconds
                  }
                  remainTimeView.textContent = "剩余时间: " + duration
                }

                var infusionStatusView = document.createElement("h3")
                if (infusionBottle.infusionStatus == 0) 
                {
                    infusionStatusView.textContent = "状态: 待输液"
                }
                else if (infusionBottle.infusionStatus == 1) 
                {
                    infusionStatusView.textContent = "状态: 输液中"
                }
                else if (infusionBottle.infusionStatus == 2)
                {
                    infusionStatusView.textContent = "状态: 暂停输液"
                }
                else if (infusionBottle.infusionStatus == 3)
                {
                    infusionStatusView.textContent = "状态: 输液完成"
                }

                child.appendChild(bottleIndexView)  // 瓶号
                child.appendChild(drugNameView)     // 药品名称
                child.appendChild(drugCapacityView) // 药品容量
                if (infusionBottle.remainCapacity != null) { 
                   child.appendChild(remainCapacityView) // 药品剩余容量
                }
                
                if (infusionBottle.remainTime != null) {                   
                    child.appendChild(remainTimeView)   // 剩余时间
                }
               
                child.appendChild(infusionStatusView) // 输液状态

                
                listDiv.appendChild(child)
            }
        }



    </script>
</head>

<body>

    <div>
        <div>
            <h1 style="color: crimson; font-size: 32px; margin-left: 15px;">输液监控平台</h1>
        </div>
        <div id="list" class="func_container">
    

        </div>

    </div>



</body>

</html>
